<template>
  <div id="login">
    <div class="form">
      <div class="title">手机号码登录</div>
      <div class="dec"></div>
      <a-form :model="loginForm" name="normal_login" class="login-form" @finish="onFinish"
        @finishFailed="onFinishFailed" ref="formRef" :rules="rules">
        <a-form-item name="phoneNumber">
          <a-input name="phone" class="pd-l pd" placeholder="请输入手机号" :bordered="false"
            v-model:value="loginForm.phoneNumber" :maxlength="11"
            @change="handleInput('phoneNumber', $event.target.value)">
          </a-input>
          <a-form-item-rest>
            <a-select class="pre" v-model:value="city" size="large" :bordered="false" @change="handleChange">
              <a-select-option :value="el.value" v-for="el in options">{{ el.label }}</a-select-option>
            </a-select>
          </a-form-item-rest>
        </a-form-item>
        <a-form-item name="smsCode" class="sms">
          <a-input type="number" class="pd-r pd" v-model:value="loginForm.smsCode" :bordered="false"
            placeholder="请输入验证码" :maxlength="6">
          </a-input>
          <div class="append" @click="getSmsCode" v-if="!inCount">获取验证码</div>
          <a-statistic-countdown class="append count-down" v-else :value="deadline" @finish="onCountFinish"
            format="ss" />
        </a-form-item>
        <a-form-item>
          <a-button :disabled="disabled" type="primary" @click="onSubmit"
            :class="[disabled ? 'nologin' : 'login', 'login-form-button']" :border="false">
            登 录
          </a-button>
        </a-form-item>
      </a-form>
      <div class="tip">未注册的手机号验证后将自动创建账号</div>
    </div>
  </div>
</template>
<script setup lang="ts">

import type { SelectProps, FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import { message } from "ant-design-vue"
import apis from "../api/index.ts"
import { useStore } from "../store/index.ts"

const router = useRouter()
const { getVerification, userLogin, userIndexStatus } = apis;
interface Form {
  phoneNumber: number | string;
  smsCode: number | string;
}
const loginForm = ref<Form>({
  phoneNumber: '',
  smsCode: '',
});
const handleInput = (types, value) => {
  console.log(types, value)
  const filteredInput = value.replace(/[^\d]/g, '').replace(/[\u4e00-\u9fa5]/, '');
  console.log(filteredInput)
  loginForm.value.phoneNumber = filteredInput;
  console.log(loginForm.value.phoneNumber)
}
const formRef = ref<FormInstance>();
// 定义不同国家（或地区）的手机号码正则表达式  
const phonePatterns = {
  '86': /^(?:13|14|15|17|18|19)\d{9}$/, // 中国大陆  
  // 可以添加更多国家  
  '65': /^[13689]\d{6,8}$/, // 新加坡
};

const city = ref<string | undefined>('86');
// 使用computed来动态计算手机号码的验证规则  
const rules = computed<Record<string, Rule[]>>(() => ({
  phoneNumber: [
    {
      required: true,
      pattern: phonePatterns[city.value] || /^$/, // 如果没有匹配的国家代码，使用一个总是匹配成功的正则表达式  
      trigger: ['change', 'blur'],
      message: '请输入正确的手机号',
    },
  ],
  smsCode: [{ required: true, message: '请输入验证码', min: 6 }],
}));

const deadline = ref<number>(Date.now() + 1000 * 60);
const options = ref<SelectProps['options']>([
  { value: '86', label: '+86' },
  { value: '65', label: '+65' },
]);
const inCount = ref<boolean>(false);

const disabled = computed(() => {
  return !(loginForm.value.phoneNumber && loginForm.value.smsCode);
});
const getSmsCode = async () => {
  if (!loginForm.value.phoneNumber) {
    return message.error("请输入手机号")
  }
  const reg = city.value === '65' ? /^[13689]\d{6,8}$/ : /^(?:13|14|15|17|18|19)\d{9}$/;
  if (!reg.test(loginForm.value.phoneNumber + '')) {
    return message.error("请输入正确的手机号")
  }
  const data: any = await getVerification({ phone: loginForm.value.phoneNumber + '' });
  console.log(data, '===>data')
  if (data && data.code === '10000') {
    inCount.value = true;
    deadline.value = Date.now() + 1000 * 60;
  } else {
    message.error(data.msg)
  }

};
const getDeadLine = () => {
  deadline.value = Date.now() + 1000 * 60;
};
const onSubmit = async () => {
  const res = await formRef.value?.validate();

  if (!res) {
    return;
  }
  const data: any = await userLogin({ phone: loginForm.value.phoneNumber + '', verifyCode: loginForm.value.smsCode });

  const store = useStore();
  if (data && data.code === '10000') {
    console.log(data, 'res');
    localStorage.setItem('token', data.data.token);

    store.$patch({
      hasLogin: true,
      userInfo: data.data,
    })
    getUserIndexStatus(data.data.userId)

    router.push('/')
  } else {
    message.error(data.msg)
  }
};

const getUserIndexStatus = async (userId) => {
  const data: any = await userIndexStatus({ userId });
  console.log(data, 'getserIndexStatus');
  if (data && data.code === '10000') {
    store.$patch({ //存储简历信息
      resumeInfo: data.data
    })
  } else {
    message.error(data.msg)
  }
}

const onCountFinish = () => {
  inCount.value = false;
};

const onFinish = (values: any) => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

const handleChange = () => { };
</script>
<style lang="scss" scoped>
#login {
  width: 100vw;
  height: calc(100vh - 72px);
  padding-top: 72px;
  box-sizing: border-box;
  background: url('../assets/img/index/index-bg.png') 100% 100% no-repeat;
  background-position: center center;
  display: flex;
  justify-content: center;
  align-items: center;
  user-select: none;
  background-size: cover;

  .form {
    width: 455px;
    height: 495px;
    background: #ffffff;
    border-radius: 15px;
    padding: 51px 33px;
    box-sizing: border-box;

    :deep(.ant-input) {
      // width: 390px;
      height: 56px;
      background: #eaeff2;
      border-radius: 8px;
      font-size: 20px;
      padding-left: 15px;
      box-sizing: border-box;
      // border: none;
    }

    .title {
      font-weight: 500;
      font-size: 24px;
      color: #28314c;
      line-height: 28px;
    }

    .dec {
      width: 144px;
      height: 4px;
      background: rgba(32, 158, 228, 0.3);
      border-radius: 60px 60px 60px 60px;
      opacity: 0.5;
      margin: 8px 0 32px 0;
    }
  }
}

.pd-l {
  padding-left: 125px !important;
}

.pd-r {
  padding-right: 150px;
}

.pd {
  position: relative;
}

.pre {
  max-width: 115px;
  position: absolute;
  left: 15px;
  top: 50%;
  transform: translateY(-50%);

  :deep(.ant-select-selector) {
    border: none;
    background: #eaeff2;
    font-size: 24px;
  }

  :deep(.ant-select-focused) {
    box-shadow: none;
  }
}

.append {
  position: absolute;
  right: 37px;
  top: 50%;
  transform: translateY(-50%);
  font-weight: 600;
  font-size: 18px;
  color: #209ee4;
  line-height: 21px;
  text-align: left;
  cursor: pointer;
}

.count-down {
  :deep(.ant-statistic-content-value) {
    color: #209ee4;
  }
}

.login-form-button {
  width: 390px;
  height: 56px;
  border-radius: 8px 8px 8px 8px;
  box-shadow: none;
  font-size: 18px;
  color: #fff;

  &:hover {
    background: #038bd4;
    border: none;
  }
}

.login {
  background: #209EE4;
}

.nologin {
  background: #79C5EF;
}

.sms {
  margin: 30px 0 50px 0;
}

.tip {
  color: #aebcc4;
  font-weight: 400;
  font-size: 18px;
  text-align: center;
  margin-top: 48px;
}

::v-deep input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;

}

::v-deep input::-webkit-outer-spin-button {
  -webkit-appearance: none !important;

}

::v-deep input[type="number"] {
  -moz-appearance: textfield;

}
</style>
